import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * @author gao
 * @date 2025/8/15 22:55
 */

public class EchoClient {
    private DatagramSocket socket;
    private String severIP;
    private int serverPort;

    public EchoClient(String serverIP, int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.severIP = serverIP;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        Scanner in = new Scanner(System.in);
        System.out.println("客户端启动:");
        while (true) {
            // 1、从控制台输入用户读取的内容
            System.out.print(">");
            String request = in.nextLine();
            // 2、构造成UDP请求，并发送
            DatagramPacket reqPacket = new DatagramPacket(request.getBytes(), request.getBytes().length, InetAddress.getByName(severIP), serverPort);
            socket.send(reqPacket);
            // 3、读取服务器的响应
            DatagramPacket resPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(resPacket);
            String response = new String(resPacket.getData(), 0, resPacket.getLength());
            // 4、把响应显示到控制台
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        EchoClient client = new EchoClient("127.0.0.1", 9090);
        client.start();
    }
}